package com.hbnu.dao;
import com.hbnu.entity.User;
import com.hbnu.util.DBUtil;
import java.sql.*;

public class UserDAO {
    // 用户注册
    public boolean register(User user) {
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO user (username, password) VALUES (?, ?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());

            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {

        }
    }

    // 用户登录
    public User login(String username, String password) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        User user = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT id, username FROM user WHERE username = ? AND password = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs!=null){
                    rs.close();
                }
            }
            catch (SQLException e){
                e.printStackTrace();
            }
        }
        return user;
    }

    // 检查用户名是否存在
    public boolean existsUsername(String username) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT id FROM user WHERE username = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            rs = pstmt.executeQuery();

            return rs.next();
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (conn!=null){
                    conn.close();
                }
            }
            catch (SQLException e){
                e.printStackTrace();
            }
            try {
                if (pstmt!=null){
                    pstmt.close();
                }
            }
            catch (SQLException e){
                e.printStackTrace();
            }
            try {
                if(rs!=null){
                    rs.close();
                }
            }
            catch (SQLException e){
                e.printStackTrace();
            }

        }
    }
}